package com.base.shiro.web;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.base.common.utils.map.MapUtil;
import com.base.shiro.entity.OrgModel;
import com.base.shiro.entity.TreeNode;
import com.base.shiro.web.validator.OrgValidator;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;

/**
 * OrgController
 * @author yuqs
 * @since 0.1
 */
public class OrgController extends Controller {
	
	public void index() {		
		render("orgList.jsp");
	}
	public void orgList(){	
//		int start=(getParaToInt("start")!=0)?getParaToInt("start"):1;
		int pageNumber=(getParaToInt("pageIndex")!=0)?getParaToInt("pageIndex")+1:1;		
		int pageSize=(getParaToInt("limit")!=0)?getParaToInt("limit"):10;		
		Page<OrgModel> orgList= OrgModel.dao.paginate(pageNumber,pageSize,getPara("name"));
		Map<String, Object> map=MapUtil.toModel("rows", orgList);
//		map.put("rows",goodsModelList.getList() );
		map.put("results",orgList.getTotalRow());
		map.put("hasError", false);		
		renderJson(map);
		
	}
	
	//组织结构数
		public void orgTree() {
			List<OrgModel> orgs = OrgModel.dao.getByParent(getParaToInt("parentId"));
			List<TreeNode> trees = new ArrayList<TreeNode>();
			TreeNode node = null;
			for(OrgModel org : orgs) {
				node = new TreeNode();
				node.setId(org.getInt("id"));
				Integer parentOrg = org.getInt("parent_org");
				node.setpId(parentOrg == null ? OrgModel.ROOT_ORG_ID : parentOrg);
				node.setName(org.getStr("name"));
				if(parentOrg == null) {
					node.setOpen(true);
				}
				trees.add(node);
			}
			renderJson(trees);
		}
	public void add() {
		render("orgAdd.jsp");
	}
	
	public void view() {
		setAttr("org", OrgModel.dao.get(getParaToInt()));
		render("orgView.jsp");
	}
	
	public void edit() {
		setAttr("org", OrgModel.dao.get(getParaToInt()));
		render("orgEdit.jsp");
	}
	
	@Before(OrgValidator.class)
	public void save() {
		getModel(OrgModel.class).save();
		redirect("/ms/shiro/org");
	}
	
	@Before(OrgValidator.class)
	public void update() {
		getModel(OrgModel.class).update();
		redirect("/ms/shiro/org");
	}
	
	public void delete() {
		OrgModel.dao.deleteById(getParaToInt());
		redirect("/ms/shiro/org");
	}
}


